#!/bin/bash
# Mojohost
# Script: zox_inst.sh
# Author: Gary Locke
#
# Description: Basic script for installing zox tube script.
# Requires: MySQL, md5sum, run as root.
#
# Usage:
#     ./script.sh <domain> </path/to/doc/root
#
# Example:
#     ./zox_inst.sh example.com /home/httpd/html/example.com/public_html
#
# Instructions:
#     Provide values for the variables after this
#     comments section and run the script as shown
#     on the usage line above. It is written in this
#     to allow for iteration over multiple domains.
#
# * 4/16/2013 Inital write.
# - 4/24/2013
#     > Reliability tweaks and testing.
#     > Checks for PDO.
#     > Checks for unique db name.
#
#### START CONFIGURATION ####

zox_zip=""       # Absolute path to ZOX ZIP (required)
cron_file=""     # Path to client's cron (e.g. /var/spool/cron/clientid)
admin_email=""   # Optional
admin_user=""    # Defaults to "admin"
admin_pass=""    # Defaults to randomly generated 8-character password
c_uid=""         # Uses 500.500 if not set

#### END CONFIGURATION ####

# Remove trailing slashes from domain names and document roots.
domain=`echo $1|sed 's/\/$//'`
doc_root=`echo $2|sed 's/\/$//'`
date=`date +"%s"`
dirName=`dirname $doc_root`
baseName=`basename $doc_root`

# Sanity checks.
if [[ `whoami` != "root" ]];then
    echo -ne "\nThis script must be run as root."; exit 1
elif ! which md5sum >/dev/null;then
    echo -ne "\nThis script requires md5sum to be installed.\n"; exit 1
elif [[ -z "$domain" ]];then
    echo -ne "\nFormat:\n./script domain /path/to/docroot\n";exit 1
elif [[ -z "$doc_root" ]];then
    echo -ne "\nFormat:\n./script domain /path/to/docroot\n";exit 1
elif [[ -z "$zox_zip" ]];then
    echo -ne "\nEdit the values at the top of the script file and try again.\n";exit 1
elif [[ ! -f "$zox_zip" ]]; then
    echo -ne "\nZox ZIP file not found. Double-check the path in the script configuration.\n";exit 1
elif ! mysql -e ";" >/dev/null 2>&1; then
    read -e -p "Please enter MySQL root pass: " mysqlRootPass
    reqPass="-p$mysqlRootPass"
    if ! mysql $reqPass -e ";" >/dev/null 2>&1; then
        read -e -p "Password incorrect, please try again: " mysqlRootPass
        reqPass="-p$mysqlRootPass"
        if ! mysql $reqPass -e ";" >/dev/null 2>&1; then
            read -e -p "Password incorrect, please try again: " mysqlRootPass
            reqPass="-p$mysqlRootPass"
            if ! mysql $reqPass -e ";" >/dev/null 2>&1; then
            echo -ne "Password incorrect. Giving up.\n"; exit 1
            fi
        fi
    fi
fi

# Generate admin user and secure password if none specified in config.
if [[ -z "$admin_pass" ]]; then
    admin_pass=`cat /dev/urandom| tr -dc a-zA-Z0-9 | fold -w 8 |head -1`
fi

if [[ -z "$admin_user" ]]; then
    admin_user="admin"
fi

# Generate salt and password values for the db.
md5_salt=`cat /dev/urandom| tr -dc a-zA-Z0-9 | fold -w 16 |head -1|md5sum|awk '{print $1}'`
md5_pass=`printf "$admin_pass$md5_salt"|md5sum|awk '{print $1}'`

# Set unique MySQL credentials before beginning install.
mysqlNameGen () {
uniqualizer=`cat /dev/urandom| tr -dc a-zA-Z0-9 | fold -w 4 |head -1`
mysqlUser=`expr substr $domain 1 6|sed 's/\./_/g'|awk '{print $1"'$uniqualizer'_zox"}'`
mysqlDb=$mysqlUser
mysqlPass=`cat /dev/urandom| tr -dc a-zA-Z0-9 | fold -w 16 |head -1`
}

mysqlNameGen

# Check that user/database name is unique.
if mysql $reqPass -e "use $mysqlDb;" >/dev/null 2>&1;then
    mysqlNameGen # Trying again...
    if mysql $reqPass -e "use $mysqlDb;" >/dev/null 2>&1;then
        echo "Can't seem to find a unique database name. Please install manually."
        exit 1
    fi
fi

set -e

# Backup existing document root directory.
cd $dirName
if [[ -d "$baseName" ]];then
    mv $baseName{,.$date}
fi

if [[ -z "$c_uid" ]];then
    c_uid=500
fi

# Create document root and set ownership.
mkdir $baseName
chown $c_uid.$c_uid $baseName
cd $baseName

# Extract data and place in docroot.
unzip -qq $zox_zip
zox_dir=`unzip -l $zox_zip|grep -m1 "zoxembed"|awk '{print $4}'|sed 's/\///'`
rsync -aq $zox_dir/ ./

# Cleanup.
set +e
rm -rf Installation\ Instructions.txt __MACOSX/ zox.zip zoxembedtube_1.0/
set -e

# Set zox script file permissions and ownership.
chown -R $c_uid.$c_uid *
chgrp -R nobody media;chmod -R 775 media
chgrp -R nobody cache;chmod -R 775 cache

# Create MySQL db, import schema, perform site setup and create admin user.
mysql $reqPass -e "create database $mysqlDb;"
mysql $reqPass -e "grant all on $mysqlDb.* to $mysqlUser@localhost identified by '$mysqlPass';"
mysql $reqPass -e "flush privileges;"
mysql $reqPass $mysqlDb < ZET_schema_1.0.sql
mysql $reqPass $mysqlDb -e "update site set title='http://$domain/', domain='http://$domain/', url='http://$domain/', salt='$md5_salt';"
mysql $reqPass $mysqlDb -e "insert into user (id,username,email,password,role,status) values (1,'$admin_user','$admin_email','$md5_pass','admin','enabled');"

# Backup default config.php and populate new configuration with db credentials.
mv app/config.php{,.$date}
printf "<?php\n\n// Database Credentials\n" >app/config.php
printf "\$db_name = '$mysqlDb';\n" >>app/config.php
printf "\$db_user = '$mysqlUser';\n" >>app/config.php
printf "\$db_pass = '$mysqlPass';\n" >>app/config.php
printf "\$db_host = 'localhost';\n\n?>" >>app/config.php
chown $c_uid.$c_uid app/config.php

# Add crons if needed.
if [[ ! -z "$cron_file" ]];then
    printf "\n# $domain\n" >> $cron_file
    printf "*/2 * * * * /usr/bin/wget -q -O /dev/null http://$domain/admin/spider/cron-populate.php\n" >> $cron_file
    printf "*/10 * * * * /usr/bin/wget -q -O /dev/null http://$domain/admin/spider/cron-crawl.php\n" >> $cron_file
    printf "0 1,13 * * * /usr/bin/wget -q -O /dev/null http://$domain/admin/spider/cron-sort.php\n" >> $cron_file

service crond restart

fi

printf "http://$domain/login.php\n$admin_user\n$admin_pass\n\n" >> /root/zox_install_creds.txt
echo -ne "\033[1;32mZox script successfully installed!\033[0m\n"
printf "Credentials appended to /root/zox_install_creds.txt ... Make sure to test them!\n"

if ! php -i 2>/dev/null|grep config|grep -- --with-pdo-mysql >/dev/null;then
    echo -ne "Note: PHP doesn't appear to be compiled with PDO support. Recompile using \"--with-pdo-mysql\".\n"
fi

exit 0
